package com.example.tests;


import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;

import org.openqa.selenium.*;

import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.PageFactory;


import com.example.pages.InternalPage;
import com.example.pages.LoginPage;
import com.example.pages.MovieAddPage;
import com.example.pages.MovieListPage;

import ru.esteru.selenium.factory.WebDriverFactory;

public class NewMovie {
  private WebDriver driver;
  private String baseUrl;
  private boolean acceptNextAlert = true;
  private StringBuffer verificationErrors = new StringBuffer();
  private LoginPage loginPage;
  private InternalPage internalPage;
  private MovieAddPage movieAddPage;
private MovieListPage movieListPage;

  @Before
  public void setUp() throws Exception {
   // driver = new FirefoxDriver();
	driver = WebDriverFactory.getDriver(DesiredCapabilities.firefox());
    baseUrl = "http://localhost/";
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
  }

  @Test
  public void testNewMovie() throws Exception {
	openloginPage();
	loginPage.loginWithValidCredentials("admin", "admin");
    addMovie("New movie", "2012", "English", "1", "1");
    logout();
  }
  
  private void addMovie(String movieName, String year, String languages, String subtitles, String audio){
		movieListPage.buttonAddMovie.click();
		movieAddPage.editName.sendKeys(movieName);
		movieAddPage.editYear.sendKeys(year);
		movieAddPage.editTextLang.sendKeys(languages);
		movieAddPage.editSubtitles.sendKeys(subtitles);
		movieAddPage.editAudio.sendKeys(audio);
		movieAddPage.buttonSubmit.click();
  }
  
  private void logout() {
	  internalPage.menuLogoutLink.click();
	  assertTrue(closeAlertAndGetItsText().matches("^Are you sure you want to log out[\\s\\S]$"));
	}

	private void openloginPage() {
		driver.get(baseUrl + "/php4dvd/");
		loginPage = PageFactory.initElements(driver, LoginPage.class);
		internalPage = PageFactory.initElements(driver, InternalPage.class);
		movieListPage = PageFactory.initElements(driver, MovieListPage.class);
		movieAddPage = PageFactory.initElements(driver, MovieAddPage.class);
	}
	
  @After
  public void tearDown() throws Exception {
    //driver.quit();
    String verificationErrorString = verificationErrors.toString();
    if (!"".equals(verificationErrorString)) {
      fail(verificationErrorString);
    }
  }

  private boolean isElementPresent(By by) {
    try {
      driver.findElement(by);
      return true;
    } catch (NoSuchElementException e) {
      return false;
    }
  }

  private String closeAlertAndGetItsText() {
    try {
      Alert alert = driver.switchTo().alert();
      if (acceptNextAlert) {
        alert.accept();
      } else {
        alert.dismiss();
      }
      return alert.getText();
    } finally {
      acceptNextAlert = true;
    }
  }
}